<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="所属企业" prop="corpId">
              <el-select
                v-model="queryParams.corpId"
                placeholder="请选择企业信息"
                style="width: 240px"
                clearable
              >
                <el-option
                  v-for="e in myCpInfos"
                  :key="e.corpId"
                  :value="e.corpId"
                  :label="e.corpName"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" border :data="jqtCpHtUserList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="唯一ID" align="center" prop="id" v-if="false" />
        <el-table-column label="客服名称" align="center" prop="name">
          <template #default="scope">
            <OpenData type='userName' :openid="scope.row.wxUserId"></OpenData>
          </template>
        </el-table-column>
        <el-table-column label="客服备注" align="center" prop="nameRemark">
          <template #default="scope">
            <span>{{scope.row.nameRemark?scope.row.nameRemark:'未定义'}}</span>
            <span @click="editNameRemarkData(scope.row)"><el-icon color="#409EFF"><EditPen /></el-icon></span>
          </template>
        </el-table-column>
        <el-table-column label="互通账号到期时间" align="center" prop="expireTime">
          <template #default="scope">
            <dict-tag :options="bus_ht_user_type" :value="scope.row.type"></dict-tag>
            <span v-if="scope.row.activeTime && scope.row.expireTime">
              ({{scope.row.activeTime}}/{{scope.row.expireTime}})
            </span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
<!--            <el-tooltip content="修改" placement="top">-->
<!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['bus:jqtCpHtUser:edit']"></el-button>-->
<!--            </el-tooltip>-->
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['bus:jqtCpHtUser:remove']">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改企业互通用户对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="jqtCpHtUserFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="企业互通ID" prop="cpHtId">
          <el-input v-model="form.cpHtId" placeholder="请输入企业互通ID" />
        </el-form-item>
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="应用id" prop="suiteId">
          <el-input v-model="form.suiteId" placeholder="请输入应用id" />
        </el-form-item>
        <el-form-item label="企业id" prop="corpId">
          <el-input v-model="form.corpId" placeholder="请输入企业id" />
        </el-form-item>
        <el-form-item label="用户名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="用户名称备注" prop="nameRemark">
          <el-input v-model="form.nameRemark" placeholder="请输入用户名称备注" />
        </el-form-item>
        <el-form-item label="微信用户id" prop="wxUserId">
          <el-input v-model="form.wxUserId" placeholder="请输入微信用户id" />
        </el-form-item>
        <el-form-item label="更新后成员所在部门列表，仅返回该应用有查看权限的部门id；成员授权模式下，仅返回根部门，即1" prop="department">
          <el-input v-model="form.department" placeholder="请输入更新后成员所在部门列表，仅返回该应用有查看权限的部门id；成员授权模式下，仅返回根部门，即1" />
        </el-form-item>
        <el-form-item label="主部门，成员授权模式下，仅返回根部门，即1" prop="mainDepartment">
          <el-input v-model="form.mainDepartment" placeholder="请输入主部门，成员授权模式下，仅返回根部门，即1" />
        </el-form-item>
        <el-form-item label="表示所在部门是否为上级，0-否，1-是，顺序与Department字段的部门逐一对应。第三方通讯录应用或者授权了“组织架构信息-应用可获取企业的部门组织架构信息-部门负责人”权限的第三方应用和代开发应用可获取；对于非第三方创建的成员，第三方通讯录应用不可获取；上游企业不可获取下游企业成员该字段" prop="isLeaderInDept">
          <el-input v-model="form.isLeaderInDept" placeholder="请输入表示所在部门是否为上级，0-否，1-是，顺序与Department字段的部门逐一对应。第三方通讯录应用或者授权了“组织架构信息-应用可获取企业的部门组织架构信息-部门负责人”权限的第三方应用和代开发应用可获取；对于非第三方创建的成员，第三方通讯录应用不可获取；上游企业不可获取下游企业成员该字段" />
        </el-form-item>
        <el-form-item label="直属上级UserID，最多1个。第三方通讯录应用或者授权了“组织架构信息-应用可获取可见范围内成员组织架构信息-直属上级”权限的第三方应用和代开发应用可获取；对于非第三方创建的成员，第三方通讯录应用不可获取；上游企业不可获取下游企业成员该字段" prop="directLeader">
          <el-input v-model="form.directLeader" placeholder="请输入直属上级UserID，最多1个。第三方通讯录应用或者授权了“组织架构信息-应用可获取可见范围内成员组织架构信息-直属上级”权限的第三方应用和代开发应用可获取；对于非第三方创建的成员，第三方通讯录应用不可获取；上游企业不可获取下游企业成员该字段" />
        </el-form-item>
        <el-form-item label="手机号码，仅通讯录管理应用可获取;代开发自建应用需要管理员授权才返回" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号码，仅通讯录管理应用可获取;代开发自建应用需要管理员授权才返回" />
        </el-form-item>
        <el-form-item label="职位信息" prop="position">
          <el-input v-model="form.position" placeholder="请输入职位信息" />
        </el-form-item>
        <el-form-item label="性别。0表示未定义，1表示男性，2表示女性。仅通讯录应用可获取" prop="gender">
          <el-input v-model="form.gender" placeholder="请输入性别。0表示未定义，1表示男性，2表示女性。仅通讯录应用可获取" />
        </el-form-item>
        <el-form-item label="邮箱，仅通讯录管理应用可获取;代开发自建应用需要管理员授权才返回" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱，仅通讯录管理应用可获取;代开发自建应用需要管理员授权才返回" />
        </el-form-item>
        <el-form-item label="头像url。注：如果要获取小图将url最后的”/0”改成”/100”即可，仅通讯录管理应用可获取" prop="avatar">
          <el-input v-model="form.avatar" placeholder="请输入头像url。注：如果要获取小图将url最后的”/0”改成”/100”即可，仅通讯录管理应用可获取" />
        </el-form-item>
        <el-form-item label="成员别名" prop="alias">
          <el-input v-model="form.alias" placeholder="请输入成员别名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="JqtCpHtUser" lang="ts">
import {
  listJqtCpHtUser,
  getJqtCpHtUser,
  delJqtCpHtUser,
  addJqtCpHtUser,
  updateJqtCpHtUser,
  editNameRemark
} from '@/api/bus/jqtCpHtUser';
import { JqtCpHtUserVO, JqtCpHtUserQuery, JqtCpHtUserForm } from '@/api/bus/jqtCpHtUser/types';
import { JqtWxInfoVO } from '@/api/bus/jqtWxInfo/types';
import { getMyWxInfo } from '@/api/bus/jqtWxInfo';
import { JqtCpHtInfoVO } from '@/api/bus/jqtCpHtInfo/types';
import { getAgentConfig, getCpList } from '@/api/bus/jqtCpHtInfo';
import { getBaseUrl } from '@/utils/ruoyi';
import { JqtCpInfoVO } from '@/api/bus/jqtCpInfo/types';
import { editRemark } from '@/api/bus/jqtCpInfo';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable,bus_ht_user_type } = toRefs<any>(proxy?.useDict('sys_normal_disable','bus_ht_user_type'));

const jqtCpHtUserList = ref<JqtCpHtUserVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const jqtCpHtUserFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: JqtCpHtUserForm = {
  id: undefined,
  remark: undefined,
  cpHtId: undefined,
  userId: undefined,
  status: undefined,
  suiteId: undefined,
  corpId: undefined,
  name: undefined,
  nameRemark: undefined,
  wxUserId: undefined,
  department: undefined,
  mainDepartment: undefined,
  isLeaderInDept: undefined,
  directLeader: undefined,
  mobile: undefined,
  position: undefined,
  gender: undefined,
  email: undefined,
  wxStatus: undefined,
  avatar: undefined,
  alias: undefined
}
const data = reactive<PageData<JqtCpHtUserForm, JqtCpHtUserQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cpHtId: undefined,
    userId: undefined,
    status: undefined,
    suiteId: undefined,
    corpId: undefined,
    name: undefined,
    nameRemark: undefined,
    wxUserId: undefined,
    department: undefined,
    mainDepartment: undefined,
    isLeaderInDept: undefined,
    directLeader: undefined,
    mobile: undefined,
    position: undefined,
    gender: undefined,
    email: undefined,
    wxStatus: undefined,
    avatar: undefined,
    alias: undefined,
    params: {
    }
  },
  rules: {
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
    cpHtId: [
      { required: true, message: "企业互通ID不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "用户id不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态(0.正常 1.停用)不能为空", trigger: "change" }
    ],
    suiteId: [
      { required: true, message: "应用id不能为空", trigger: "blur" }
    ],
    corpId: [
      { required: true, message: "企业id不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "用户名称不能为空", trigger: "blur" }
    ],
    nameRemark: [
      { required: true, message: "用户名称备注不能为空", trigger: "blur" }
    ],
    wxUserId: [
      { required: true, message: "微信用户id不能为空", trigger: "blur" }
    ],
    department: [
      { required: true, message: "更新后成员所在部门列表，仅返回该应用有查看权限的部门id；成员授权模式下，仅返回根部门，即1不能为空", trigger: "blur" }
    ],
    mainDepartment: [
      { required: true, message: "主部门，成员授权模式下，仅返回根部门，即1不能为空", trigger: "blur" }
    ],
    isLeaderInDept: [
      { required: true, message: "表示所在部门是否为上级，0-否，1-是，顺序与Department字段的部门逐一对应。第三方通讯录应用或者授权了“组织架构信息-应用可获取企业的部门组织架构信息-部门负责人”权限的第三方应用和代开发应用可获取；对于非第三方创建的成员，第三方通讯录应用不可获取；上游企业不可获取下游企业成员该字段不能为空", trigger: "blur" }
    ],
    directLeader: [
      { required: true, message: "直属上级UserID，最多1个。第三方通讯录应用或者授权了“组织架构信息-应用可获取可见范围内成员组织架构信息-直属上级”权限的第三方应用和代开发应用可获取；对于非第三方创建的成员，第三方通讯录应用不可获取；上游企业不可获取下游企业成员该字段不能为空", trigger: "blur" }
    ],
    mobile: [
      { required: true, message: "手机号码，仅通讯录管理应用可获取;代开发自建应用需要管理员授权才返回不能为空", trigger: "blur" }
    ],
    position: [
      { required: true, message: "职位信息不能为空", trigger: "blur" }
    ],
    gender: [
      { required: true, message: "性别。0表示未定义，1表示男性，2表示女性。仅通讯录应用可获取不能为空", trigger: "blur" }
    ],
    email: [
      { required: true, message: "邮箱，仅通讯录管理应用可获取;代开发自建应用需要管理员授权才返回不能为空", trigger: "blur" }
    ],
    wxStatus: [
      { required: true, message: "激活状态: 1=已激活，2=已禁用，4=未激活，5=退出企业。已激活代表已激活企业微信或已关注微信插件不能为空", trigger: "change" }
    ],
    avatar: [
      { required: true, message: "头像url。注：如果要获取小图将url最后的”/0”改成”/100”即可，仅通讯录管理应用可获取不能为空", trigger: "blur" }
    ],
    alias: [
      { required: true, message: "成员别名不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询企业互通用户列表 */
const getList = async () => {
  loading.value = true;
  const res = await listJqtCpHtUser(queryParams.value);
  jqtCpHtUserList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  await getAgentConfigInfo();
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  jqtCpHtUserFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getMyCpInfoData();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: JqtCpHtUserVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加企业互通用户";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: JqtCpHtUserVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getJqtCpHtUser(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改企业互通用户";
}

/** 提交按钮 */
const submitForm = () => {
  jqtCpHtUserFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateJqtCpHtUser(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addJqtCpHtUser(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: JqtCpHtUserVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除企业互通用户编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delJqtCpHtUser(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('bus/jqtCpHtUser/export', {
    ...queryParams.value
  }, `jqtCpHtUser_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getMyCpInfoData();
});

const myCpInfos = ref<JqtCpHtInfoVO[]>([]);
/**
 * 获取企业信息
 */
const getMyCpInfoData = async () => {
  const res = await getCpList();
  myCpInfos.value = res.data;
  if(myCpInfos.value.length > 0){
    queryParams.value.corpId = myCpInfos.value[0].corpId;
  }
  await getList();
};
/**
 * 获取应用配置信息
 */
const getAgentConfigInfo = async () =>{
  const res = await getAgentConfig(window.location.href,queryParams.value.corpId);
  wx.agentConfig({
    corpid: res.data.appId, // 必填，企业微信的corpid，必须与当前登录的企业一致
    agentid: res.data.agentid, // 必填，企业微信的应用id （e.g. 1000247）
    timestamp: res.data.timestamp, // 必填，生成签名的时间戳
    nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
    signature: res.data.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
    jsApiList: ['WWOpenData'], //必填，传入需要使用的接口名称
    success: function (result) {
      console.log(result,'请求微信成功')
      // 回调
    },
    fail: function (e) {
      if (e.errMsg.indexOf('function not exist') > -1) {
        proxy?.$modal.msgError('请升级企业微信版本')
      }
    },
  });
}



/** 编辑备注 */
const editNameRemarkData = async (row?: JqtCpHtUserVO) => {
  const _ids = row?.id || ids.value;
  ElMessageBox.prompt('修改客服成员备注', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
    .then(async ({ value }) => {
      await editNameRemark({
        id: row?.id,
        nameRemark: value
      });
      proxy?.$modal.msgSuccess("设置成功");
      row.nameRemark = value;
    })
    .catch(() => {
    })
}
</script>
